<?php
/**
 * YICMS
 * ============================================================================
 * 版权所有 2014-2017 YICMS，并保留所有权利。
 * 网站地址: http://www.yicms.vip
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Created by PhpStorm.
 * Author: kenuo
 * Date: 2017/11/17
 * Time: 下午2:30
 */

namespace App\Models\Traits;

use App\Handlers\Tree;
use App\Models\Config\Servers;
use App\Repositories\RulesRepository;
use Cache;

trait RbacCheck
{
    // 缓存相关配置
    protected $cache_key = '_cache_rules';

    protected $menu_cache = '_menu_cache'; //菜单缓存key

    protected $game_cache = '_game_cache'; //游戏缓存key

    protected $channel_cache = '_channel_cache'; //渠道缓存key

    protected $server_cache = '_server_cache'; //服务器缓存key

    /**
     * 获取当前用户的所有游戏权限
     * @return mixed
     */
    public function getGames()
    {
        $cache_key = $this->id . $this->game_cache;

        if (!Cache::tags(['games'])->has($cache_key)) {
            $permissions = $this->games()->get()->pluck('game_name', 'game_id')->toArray();

            /**将权限路由存入缓存中*/
            Cache::tags(['games'])->forever($cache_key, $permissions);

            return $permissions;
        }

        return Cache::tags(['games'])->get($cache_key);
    }

    /**
     * 获取当前用户的所有渠道权限
     * @return mixed
     */
    public function getChannels($condition = [], $key = 'id')
    {
        $game_id = session('game_id');
        $cache_key = "id_{$this->id}_game_id_{$game_id}{$this->channel_cache}_{$key}";

        if (!Cache::tags(['channels'])->has($cache_key)) {

            $permissions = $this->channels()->where($condition)->get()->pluck('channel_name', $key)->toArray();
            ksort($permissions);

            /**将权限路由存入缓存中*/
            Cache::tags(['channels'])->forever($cache_key, $permissions);

            return $permissions;
        }

        return Cache::tags(['channels'])->get($cache_key);
    }

    /**
     * 获取当前用户的所有 服务器列表 的 unique_id
     * @return mixed
     */
    public function getServers()
    {
        $game_id = session('game_id');
        $cache_key = "id_{$this->id}_game_id_{$game_id}{$this->server_cache}";

        if (!Cache::tags(['servers'])->has($cache_key)) {

            $servers = $this->_getAllServer();

            Cache::tags(['servers'])->put($cache_key, $servers, env('CACHE_EXPIRE_TIME', 10));

            return $servers;
        }

        return Cache::tags(['servers'])->get($cache_key);
    }

    /**
     * 获取当前用户的所有权限
     * @return mixed
     */
    public function getRules()
    {
        $cache_key = $this->id . $this->cache_key;

        if (!Cache::tags(['rbac', 'rules'])->has($cache_key)) {

            $permissions = $this->rules()->pluck('route')->toArray();

            /**将权限路由存入缓存中*/
            Cache::tags(['rbac', 'rules'])->forever($cache_key, $permissions);

            return $permissions;
        }

        return Cache::tags(['rbac', 'rules'])->get($cache_key);
    }

    /**
     * 获取树形菜单导航栏
     * @return array
     */
    public function getMenus()
    {
        $menu_cache = $this->id . $this->menu_cache;

        if (!Cache::tags(['rbac', 'menus'])->has($menu_cache)) {
            $rules = [];
            //判断是否是超级管理员用户组
            if ($this->id == 1) {
                //超级管理员用户组获取全部权限数据
                $rules = (new RulesRepository())->getRulesAndPublic()->toArray();

            } else {
                $rules = $this->rules()->public()->orderBy('sort', 'asc')->get()->toArray();
            }

            /**将权限路由存入缓存中*/
            Cache::tags(['rbac', 'menus'])->forever($menu_cache, $rules);
        } else {
            $rules = Cache::tags(['rbac', 'menus'])->get($menu_cache);
        }

        return Tree::array_tree($rules);
    }

    /**
     * 删除权限缓存和菜单缓存
     * @return bool
     */
    public function clearRuleAndMenu()
    {
        return Cache::tags('rbac')->flush();
    }

    public function clearGames()
    {
        return Cache::tags('games')->flush();
    }

    public function clearChannels()
    {
        return Cache::tags('channels')->flush();
    }

    /**
     * 获取全部的 服务器
     * @return mixed
     */
    public function _getAllServer()
    {
        $gameID = session('game_id');
        $channelAuth = array_keys($this->getChannels(['game_id' => $gameID], 'channel_id'));
        foreach ($channelAuth as $key => $value) {
            $channelAuth[$key] = strval($value);
        }

        $query = [
            [
                '$match' =>
                    [
                        'game_id' =>
                            [
                                '$eq' => $gameID
                            ],
                        'channel_id' => [
                            '$in' => $channelAuth
                        ]
                    ]
            ],
            [
                '$project' =>
                    [
                        '_id' => 0,
                        'unique_id' =>
                            [
                                '$concat' => ['$channel_id', '-', '$sub_channel_id', '-', '$server_id']
                            ],
                        'channel_id' => '$channel_id',
                        'sub_channel_id' => '$sub_channel_id',
                        'server_id' => '$server_id',
                        'game_name' => '$game_name',
                        'channel_name' => '$channel_name',
                        'server_name' => '$server_name',
                        'update_time' => '$update_time',
                    ]
            ],
            [
                '$sort' =>
                    [
                        'server_id' => 1
                    ]
            ]
        ];

        $collection = Servers::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });

        return $collection->toArray();
    }
}